<template>
	<!-- 我拥有的商品 -->
	<view>
		<view class="record" :style="colorStyle" v-if="visitList.length">
			<view class="nav acea-row row-between-wrapper">
				<view class="left">{{$t(`共`)}} <text class="num">{{totalCount}}</text>{{$t(`件商品`)}}</view>
				<view class="font-num" v-if="!isShowChecked" @click="switchTap">{{$t(`管理`)}}</view>
				<view v-else @click="switchTap">{{$t(`取消`)}}</view>
			</view>
			<view class="list">
				<checkbox-group @change="checkboxChange">
					<view class="item" v-for="(item, index) in visitList" :key="index">
						<view class="title">
							<checkbox v-if="isShowChecked" :value="item.time" :checked="item.checked" />
							<text>{{item.time}}</text>
						</view>
						<checkbox-group @change="(e) => picCheckbox(e, index)">
							<view class="picList acea-row row-middle">
								<view class="picTxt" v-for="(j, jindex) in item.picList" :key="jindex"
									@click.stop="goDetails(j)">
									<view class="pictrue">
										<image :src="j.image"></image>
										<checkbox v-if="isShowChecked" :value="j.unique" :checked="j.checked"
											class="checkbox" />
										<view class="masks acea-row row-center-wrapper"
											v-if="!isShowChecked && (j.stock <= 0 || j.trueStock <= 0)">
											<view class="bg">
												<view>{{$t(`已售罄`)}}</view>
											</view>
										</view>
										<view class="masks acea-row row-center-wrapper"
											v-if="!isShowChecked && !j.is_show">
											<view class="bg">
												<view>{{$t(`已下架`)}}</view>
											</view>
										</view>
									</view>
									<view class="money">¥<text class="num">{{j.truePrice || j.price}}</text></view>
								</view>
							</view>
						</checkbox-group>
					</view>
				</checkbox-group>
				<view class='loadingicon acea-row row-center-wrapper'>
					<text class='loading iconfont icon-jiazai' :hidden='loading==false'></text>{{loadTitle}}
				</view>
			</view>
			<view class="footer acea-row row-between-wrapper" v-if="isShowChecked">
				<checkbox-group @change="checkboxAllChange">
					<checkbox value="all" :checked="isAllSelect" />
					<text class='checkAll'>{{$t(`全选`)}}</text>
				</checkbox-group>
				<view class="acea-row row-middle">
					<view class="bnt on acea-row row-center-wrapper" @click="del">{{$t(`删除`)}}</view>
				</view>
			</view>
		</view>
		<view class='noCommodity' v-else-if="!visitList.length && page == 2">
			<view class='pictrue'>
				<image :src="imgHost + '/statics/images/no-thing.png'"></image>
			</view>
			<view class="acea-row row-center-wrapper tip">{{$t(`暂无数据`)}}</view>
			<recommend :hostProduct="hostProduct"></recommend>
		</view>
	</view>
</template>

<script>
	import { getOrderList } from '@/api/order.js';
	import {
		getProductHot
	} from '@/api/store.js';
	import {
		mapGetters
	} from "vuex";
	import {
		toLogin
	} from '@/libs/login.js';
	import recommend from '@/components/recommend';
	import home from '@/components/home';
	import colors from '@/mixins/color.js';
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';

	export default {
		components: {
			recommend,
			home,
		},
		mixins: [colors],
		data() {
			return {
				isShowChecked: 0,
				totalCount: 0,
				times: [],
				isAllSelect: false,
				hostProduct: [],
				loadTitle: this.$t(`加载更多`),
				loading: false,
				loadend: false,
				visitList: [],
				limit: 20,
				page: 1,
				imgHost: HTTP_REQUEST_URL
			};
		},
		computed: mapGetters(['isLogin']),
		onLoad() {
			if (this.isLogin) {
				this.loadend = false;
				this.page = 1;
				this.visitList = [];
				this.times = [];
				this.get_user_owned_list();
				this.get_host_product();
			} else {
				toLogin();
			}
		},
		onShow() {
			uni.removeStorageSync('form_type_cart');
			this.times = [];
			this.loadend = false;
			this.page = 1;
			this.visitList = [];
			this.get_user_owned_list();
		},
		methods: {
			goDetails(item) {
				if (this.isShowChecked || !item.is_show) return false;
				// 跳转到订单详情
				uni.navigateTo({
					url: `/pages/goods/order_details/index?order_id=${item._order_id}`
				});
			},
			switchTap() {
				this.isShowChecked = !this.isShowChecked;
				// 同步 checked 状态
				this.visitList.forEach(group => {
					group.checked = this.isShowChecked ? false : group.checked;
					group.picList.forEach(good => {
						good.checked = this.isShowChecked ? false : good.checked;
					});
				});
			},
			del() {
				// 注意：实际“拥有的商品”通常不可删除，此处保留原逻辑结构
				// 你可以后续替换为提示或禁用
				let ids = [];
				this.visitList.forEach(item => {
					item.picList.forEach(j => {
						if (j.checked) {
							ids.push(j._order_id); // 或其他标识
						}
					});
				});
				if (!ids.length) {
					return this.$util.Tips({
						title: '请选择删除商品'
					});
				}
				// 实际不调用删除接口，仅提示
				this.$util.Tips({
					title: '订单商品不可删除'
				});
			},
			picCheckbox(event, index) {
				let that = this,
					picTime = event.detail.value;
				that.visitList[index].picList.forEach(j => {
					if (picTime.indexOf(j.unique) !== -1) {
						j.checked = true;
					} else {
						j.checked = false;
					}
				});
				if (that.visitList[index].picList.length === picTime.length) {
					that.visitList[index].checked = true;
				} else {
					that.visitList[index].checked = false;
				}
				let visitObj = [];
				that.visitList.forEach(item => {
					if (item.checked) {
						visitObj.push(item.time);
					}
				});
				that.isAllSelect = visitObj.length === that.visitList.length;
			},
			checkboxChange(event) {
				let that = this,
					timeList = event.detail.value;
				that.visitList.forEach((item, index) => {
					item.checked = timeList.indexOf(item.time) !== -1;
					item.picList.forEach(j => {
						j.checked = item.checked;
					});
				});
				that.isAllSelect = timeList.length === that.visitList.length;
			},
			forGoods(val) {
				let that = this;
				if (!that.visitList.length) return;
				that.visitList.forEach(item => {
					item.checked = val;
					item.picList.forEach(j => {
						j.checked = val;
					});
				});
			},
			checkboxAllChange(event) {
				let value = event.detail.value;
				if (value.length) {
					this.isAllSelect = true;
					this.forGoods(1);
				} else {
					this.isAllSelect = false;
					this.forGoods(0);
				}
			},
			/**
			 * 获取我拥有的商品（按订单时间分组）
			 */
			get_user_owned_list() {
				let that = this;
				if (this.loading || this.loadend) return;
				this.loading = true;
				this.loadTitle = "";

				getOrderList({
					type: 3,
					page: that.page,
					limit: that.limit
				}).then(res => {
					if (res.status !== 200) {
						that.loading = false;
						that.loadTitle = that.$t(`加载更多`);
						return;
					}

					const orders = res.data || [];
					const newTimeMap = {};

					// 遍历订单，按 _add_time（格式如 "2025-10-05 16:34:35"）提取日期分组
					orders.forEach(order => {
						if (!order._add_time) return;
						const dateKey = order._add_time.split(' ')[0]; // "2025-10-05"

						if (!newTimeMap[dateKey]) {
							newTimeMap[dateKey] = [];
						}

						if (order.cartInfo && Array.isArray(order.cartInfo)) {
							order.cartInfo.forEach(cartItem => {
								const productInfo = cartItem.productInfo || {};
								const attrInfo = cartItem.attrInfo || {};

								const image = attrInfo.image || productInfo.image;
								const price = cartItem.truePrice || cartItem.sum_true_price ||
									attrInfo.price || productInfo.price;
								const stock = attrInfo.stock || productInfo.stock;
								const is_show = productInfo.is_show !== undefined ? productInfo
									.is_show : true;

								newTimeMap[dateKey].push({
									...cartItem,
									...productInfo,
									...attrInfo,
									image,
									price,
									stock,
									is_show,
									truePrice: cartItem.truePrice || cartItem
										.sum_true_price,
									_order_id: order.order_id,
									unique: cartItem.unique || attrInfo.unique || (
										productInfo.id + ''),
									checked: false,
									product_price: price // 兼容原字段
								});
							});
						}
					});

					// 合并到现有 visitList
					Object.keys(newTimeMap).forEach(date => {
						if (this.times.indexOf(date) === -1) {
							this.times.push(date);
							this.visitList.push({
								time: date,
								picList: newTimeMap[date],
								checked: false
							});
						} else {
							// 已存在日期，追加商品（分页场景）
							const idx = this.times.indexOf(date);
							this.visitList[idx].picList.push(...newTimeMap[date]);
						}
					});

					// 重新计算总数
					this.totalCount = this.visitList.reduce((sum, group) => sum + group.picList.length, 0);

					const loadend = orders.length < that.limit;
					that.loadend = loadend;
					that.loadTitle = loadend ? that.$t(`没有更多内容啦~`) : that.$t(`加载更多`);
					that.page++;
					that.loading = false;
				}).catch(err => {
					console.error('获取拥有的商品失败', err);
					that.loading = false;
					that.loadTitle = that.$t(`加载更多`);
				});
			},
			/**
			 * 获取推荐商品
			 */
			get_host_product() {
				let that = this;
				if (that.hotScroll) return;
				getProductHot(
					that.hotPage,
					that.hotLimit,
				).then(res => {
					that.hotPage++;
					that.hotScroll = res.data.length < that.hotLimit;
					that.hostProduct = that.hostProduct.concat(res.data);
				});
			}
		},
		onReachBottom() {
			if (this.visitList.length) {
				this.get_user_owned_list();
			} else {
				this.get_host_product();
			}
		},
		onPageScroll(e) {
			uni.$emit('scroll');
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.noCommodity .pictrue {
		width: 414rpx;
		height: 304rpx;
		margin: 30rpx auto 0 auto;

		.tip {
			color: #bbb;
			font-size: 25rpx;
		}
	}

	.record .pictrue /deep/ checkbox .uni-checkbox-input {
		background-color: rgba(0, 0, 0, 0.16);
	}

	.record .pictrue /deep/ checkbox .wx-checkbox-input {
		background-color: rgba(0, 0, 0, 0.16);
	}

	.record {
		.footer {
			box-sizing: border-box;
			padding: 0 30rpx;
			width: 100%;
			height: 96rpx;
			box-shadow: 0px -4px 20px 0px rgba(0, 0, 0, 0.06);
			background-color: #fff;
			position: fixed;
			bottom: 0;
			z-index: 30;
			height: calc(96rpx + constant(safe-area-inset-bottom));
			height: calc(96rpx + env(safe-area-inset-bottom));
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);

			.bnt {
				width: 160rpx;
				height: 60rpx;
				border-radius: 30rpx;
				border: 1rpx solid #ccc;
				color: #666666;

				&.on {
					border: 1rpx solid var(--view-theme);
					margin-left: 16rpx;
					color: var(--view-theme);
				}
			}
		}

		.nav {
			border-bottom: 1rpx solid #eee;
			color: #999999;
			font-size: 28rpx;
			height: 74rpx;
			padding: 0 30rpx;

			.left {
				color: #333;

				.num {
					color: var(--view-theme);
					margin: 0 10rpx;
				}
			}
		}

		.list {
			padding-top: 32rpx;
			padding-bottom: 96rpx;

			.item {
				.title {
					padding: 0 30rpx;
					margin-bottom: 34rpx;
					font-size: 34rpx;
					font-weight: 600;
				}

				.picList {
					padding: 0 30rpx 0 12rpx;

					.picTxt {
						margin-left: 18rpx;
						margin-bottom: 48rpx;

						.pictrue {
							width: 218rpx;
							height: 218rpx;
							border-radius: 10rpx;
							position: relative;

							image {
								width: 100%;
								height: 100%;
								border-radius: 10rpx;
							}

							.masks {
								position: absolute;
								top: 0;
								left: 0;
								right: 0;
								bottom: 0;
								background: rgba(0, 0, 0, 0.2);
								border-radius: 10rpx;

								.bg {
									width: 110rpx;
									height: 110rpx;
									background: #000000;
									opacity: 0.6;
									color: #fff;
									font-size: 22rpx;
									border-radius: 50%;
									line-height: 110rpx;
									text-align: center;
								}
							}

							.checkbox {
								position: absolute;
								right: 10rpx;
								top: 14rpx;
							}
						}

						.money {
							font-size: 24rpx;
							color: var(--view-priceColor);
							font-weight: 600;
							margin-top: 15rpx;

							.num {
								font-size: 32rpx;
								margin-left: 6rpx;
							}
						}
					}
				}
			}
		}
	}
</style>